from lib.funcs import *

import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as msbox
import json
import requests
import pyperclip
import urllib
import hashlib
import random

tran_dict = {
    '自动检测': 'auto',
    '中文': 'zh',
    '英语': 'en',
    '粤语': 'yue',
    '文言文': 'wyw',
    '日语': 'jp',
    '韩语': 'kor',
    '法语': 'fra',
    '西班牙语': 'spa',
    '泰语': 'th',
    '阿拉伯语': 'ara',
    '俄语': 'ru',
    '葡萄牙语': 'pt',
    '德语': 'de',
    '意大利语': 'it',
    '希腊语': 'el',
    '荷兰语': 'nl'	,
    '波兰语': '	pl',
    '保加利亚语': 'bul',
    '爱沙尼亚语': 'est',
    '丹麦语': 'dan',
    '芬兰语': 'fin',
    '捷克语': 'cs',
    '罗马尼亚语': 'rom',
    '斯洛文尼亚语':	'slo',
    '瑞典语': 'swe',
    '匈牙利语': 'hu',
    '繁体中文': 'cht',
    '越南语': 'vie'
}
tran_list = list(tran_dict.keys())


class NetworkError(Exception):
    '''网络连接异常类'''

    def __init__(self, why):
        self.why = why

    def __str__(self):
        return self.why


class RequestError(Exception):
    '''获取响应错误类'''

    def __init__(self, why):
        self.why = why

    def __str__(self):
        return self.why


class class_tran:
    '''翻译类'''

    def __init__(self):
        pass

    def translate(self, data, appid, key, fro, to) -> str:
        '''使用Baidu进行翻译'''
        ans = 0
        try:
            salt = random.randint(0, 1000000)
            str_1 = appid + data + str(salt) + key
            str_1 = hashlib.md5(str_1.encode("UTF-8")).hexdigest()
            ans = requests.get(
                f"http://api.fanyi.baidu.com/api/trans/vip/translate?q={data}&from={fro}&to={to}&appid={appid}&salt={salt}&sign={str_1}")
        except requests.exceptions.ConnectionError as w:
            raise NetworkError(f"[ERROR]没有网络连接{w}")  # 没有网络连接

        if (ans.status_code != 200):
            raise RequestError("[ERROR]响应：" + ans.status_code)  # 响应错误
        ans = ans.json()
        try:
            ans = ans["trans_result"][0]['dst']
        except KeyError:
            if ans['error_code'] == '58001':
                raise RequestError("不支持该翻译语言,检查语言代码")
            raise RequestError(ans)

        return ans


class GUI_tran:
    '''图形界面管理类-翻译界面'''

    def __init__(self, father, sitting) -> None:
        '''初始化'''
        self.sitting = sitting["modules"]["tran"]
        self.window = father

        self.__init__component()

    def __init__component(self):
        '''初始化组件'''
        self._dat_outbox = tk.StringVar()

        self.btfrme = tk.Frame(self.window)  # 两大框架
        self.boxframe = tk.Frame(self.window)

        self.inbox = entry(self.boxframe, "input_box", self.sitting)

        self.outbox = label(self.boxframe, "output_box", self.sitting, self._dat_outbox)

        self.runnnnn = button(
            self.btfrme, command=self.__when_button_clicked, nameof="tran_button", sitting=self.sitting
        )  # 设置翻译按钮

        self.cpbutton = button(
            self.btfrme, command=self.__copy_to_clipborad, nameof="copy_button", sitting=self.sitting
        )# 设置拷贝到剪贴板按钮

        self.extrafunc = button(
            self.window, command=self.__copy_comment_to_clipborad, nameof="comm_button", sitting=self.sitting
        )

        self.inbox.pack(side=tk.TOP)
        self.outbox.pack(side=tk.BOTTOM)
        self.boxframe.pack(side=tk.TOP)

        self.btfrme.pack(side=tk.TOP)
        self.runnnnn.pack(side=tk.RIGHT)
        self.cpbutton.pack(side=tk.LEFT)
        self.extrafunc.pack(side=tk.TOP)

        self.fro = "auto"
        self.to = "en"
        self.config_frame = tk.Frame(self.window)
        self.tran_from = ttk.Combobox(self.config_frame)
        self.tran_from["value"] = tran_list
        self.tran_from.current(0)
        self.tran_from.bind("<<ComboboxSelected>>", self.__set_tran_from)
        self.tran_from.pack(side=tk.LEFT)
        self.tran_to = ttk.Combobox(self.config_frame)
        self.tran_to["value"] = tran_list[1:]
        self.tran_to.current(1)
        self.tran_to.pack(side=tk.RIGHT)
        self.tran_to.bind("<<ComboboxSelected>>", self.__set_tran_to)

        self.config_frame.pack(side=tk.BOTTOM)

        self.func = class_tran()  # 全部加载

    def __when_button_clicked(self):
        '''处理按下按钮事件'''
        input_box_data = str(self.inbox.get())
        if len(input_box_data) == 0:
            msbox.showerror(title='Error!', message='未输入字符！')
        else:  # 是文字
            self.func_run()

    def func_run(self):
        '''进行翻译'''
        try:
            ans = self.func.translate(
                str(self.inbox.get()), key=self.sitting["key"], appid=self.sitting["appid"], fro=self.fro, to=self.to)
        except NetworkError as w:
            msbox.showerror(title='Error!', message=f'出错了！\n{w.why}')
        except RequestError as w:
            msbox.showerror(title='Error!', message=f'出错了！\n{w.why}')
        # else:e
            # ans = ' '
        self._dat_outbox.set(ans)

    def __copy_to_clipborad(self):
        '''复制到剪贴板'''
        pyperclip.copy(self._dat_outbox.get())

    def __copy_comment_to_clipborad(self):
        '''复制到剪贴板'''
        pyperclip.copy(self.sitting["comment_style"] +
                       ' ' + self._dat_outbox.get())

    def __set_tran_from(self, event):
        self.tra = tran_dict[self.tran_from.get()]

    def __set_tran_to(self, event):
        self.to = tran_dict[self.tran_to.get()]

    def __clear__input__box(self):
        self.inbox.delete(0, tk.END)
